package com.zhiyin.daodejing;

import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;

import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.widget.RelativeLayout.LayoutParams;

public class MainActivity extends AppCompatActivity{
    private ListView listView;
    private SimpleAdapter simpleAdapter;
    private ArrayList<Map<String,Object>> data;
    private Map<String,Object> map;

    private InputStreamReader inputStreamReader;
    private BufferedReader bufferedReader;
    private StringBuilder stringBuilder;

    private DrawerLayout drawer_layout;
    private  Toolbar toolBar;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolBar = findViewById(R.id.toolBar);
        setSupportActionBar(toolBar);
        //响应工具栏按钮点击事件
        toolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener(){
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_h:
                        drawer_layout.openDrawer(Gravity.START);
                        drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
                                Gravity.START);    //解除锁定
                        break;
                }
                return true;
            }
        });



        drawer_layout =  findViewById(R.id.drawer_layout);

        //默认隐藏侧边栏
        drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                Gravity.START);

        setListView("article.json");

    }

    private void setListView(String str){
        //获取xml控件id
        listView = findViewById(R.id.listView);

        //初始化数据源
        data = new ArrayList<Map<String,Object>>();

        try {
            //读取文件，字节流转 字符串
            inputStreamReader = new InputStreamReader(getAssets().open(str),"utf-8");
            //字符缓冲，提升速度
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            //定义可变字符变量
            stringBuilder = new StringBuilder();
            while ( (line = bufferedReader.readLine()) != null){
                stringBuilder.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();

            try {
                //字符串转换json对象
                JSONObject jsonObject = new JSONObject(stringBuilder.toString());
                ////从JSONObject中取出数组对象
                JSONArray jsonArray = jsonObject.getJSONArray("key");

                for (int i=0;i<jsonArray.length();i++){
                    JSONObject article_list = jsonArray.getJSONObject(i);//取出数组中的对象
                    map = new HashMap<String, Object>();
                    map.put("_id",article_list.getInt("id")); //取出数组中对象的各个值
                    map.put("title",article_list.getString("post_title"));
                    map.put("post_excerpt",article_list.getString("post_excerpt"));
                    map.put("post_content",article_list.getString("post_content"));
                    data.add(map);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        String[] from = {"title"};
        int[] to = {R.id.title};

        simpleAdapter = new SimpleAdapter(MainActivity.this,data,R.layout.simpleadapter_item,from,to);
        //赋值
        listView.setAdapter(simpleAdapter);

        TextView desc = findViewById(R.id.title);
        String st = "<h2 style='text-align: center'>《道德经》</h2><p style='line-height: 2rem;text-index:5rem;font-size: 8rem'>《道德经》又称《老子》，是中国古代先秦诸子分家前的一部著作，为其时诸子所共仰，传说是春秋时期的老子李耳所撰写，是道家哲学思想的重要来源。道德经分上下两篇，原文上篇《德经》、下篇《道经》，不分章，后改为《道经》在前，《德经》在后，并分为81章,全文共约五千字，是中国历史上首部完整的哲学著作。\n"+
                "　　<br/>《道德经》常会被归属为道教学说。其实哲学上的道家，和宗教上的道教，是不能混为一谈的，但《道德经》作为道教基本教义的重要构成之一，被道教视为重要经典，其作者老子也被道教视为至上的三清尊神之一道德天尊的化身，又称太上老君，所以应该说道教吸纳了道家思想，道家思想完善了道教。同时，前面所说的哲学，并不能涵括《道德经》（修身立命、治国安邦、出世入世）的全貌。<br/>《道德经》提出了“无为而治”的主张,无为而治是道家的基本思想，也是其修行的基本方法。作为一种政治原则，“无为”在春秋末期已经出现。儒家也讲“无为而治”，如《论语·卫灵公》：“无为而治者，其舜也与？夫何为哉？恭己正南面而已矣”。朱熹认为“圣人德盛而民化，不待其有所作为也。“，实则表达了儒家的德治主张。使“无为而治”系统化而成为理论的是《老子》。他们认为统治者的一切作为都会破坏自然秩序，扰乱天下，祸害百姓。要求统治者无所作为，效法自然，让百姓自由发展。“无为而治”的理论根据是“道”，现实依据是变“乱”为“治”；“无为而治”的主要内容是“为无为”和“无为而无不为”，具体措施是“劝统治者少干涉”和“使民众无知无欲”。\n" +
                "　<br/>《道德经》并不像一般人所理解的那样，是一部论述道德的著作。事实上，道德二字各有不同的概念。道德经前三十七章讲道，后四十四章言德，简单说来，道是体，德是用，二者不能等同。</p>";
        desc.setText(Html.fromHtml(st));
        desc.setGravity(2);



        //监听单击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //1.获取listview 里的值
                //TextView  textView = view.findViewById(R.id._id);
                //String _id = textView.getText().toString();
                //Toast.makeText(MainActivity.this,"heheh"+_id,Toast.LENGTH_LONG).show();


                //2.获取listview 里的值
                //Map item = (Map)parent.getItemAtPosition(position);
                //Toast.makeText(MainActivity.this,"heheh"+item.get("post_content"),Toast.LENGTH_LONG).show();

                Map item = (Map)parent.getItemAtPosition(position);
//                Intent intent = new Intent(MainActivity.this,ArticleActivity.class);
//                intent.putExtra("title",item.get("title").toString());
//                intent.putExtra("post_excerpt",item.get("post_excerpt").toString());
//                intent.putExtra("post_content",item.get("post_content").toString());
//                startActivity(intent);

                TextView yuan_wen = findViewById(R.id.yuan_wen);
                yuan_wen.setText("原文");

                TextView yi_wen = findViewById(R.id.yi_wen);
                yi_wen.setText("译文");

                String str_title = item.get("title").toString();
                String post_excerpt = item.get("post_excerpt").toString();
                String post_content = item.get("post_content").toString();

                TextView textView_title = findViewById(R.id.title);
                textView_title.setText(str_title);
                textView_title.setGravity(1);

                TextView textView = findViewById(R.id.textView);
                textView.setText(post_excerpt);

                WebView webView = findViewById(R.id.webView);

                //解码成html 元素
                String html = Html.fromHtml(post_content).toString();


                webView.getSettings().setJavaScriptEnabled(true);
                webView.loadDataWithBaseURL(null,html,"text/html","utf-8",null);
                webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                webView.setBackgroundColor(0);
                webView.getBackground().setAlpha(0);
                if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
                    drawer_layout.closeDrawer(GravityCompat.START);
                }
                //滚动条，到顶部
                scrollView = findViewById(R.id.scroll_view);
                scrollView.fullScroll(View.FOCUS_UP);

            }
        });
    }

    //    加载工具toolbar菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    //    点击侧边栏以外，隐藏侧边栏
    @Override
    public void onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}
